﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CMS6Tools.IISServer
{
    public partial class ShowChartForm : Form
    {
        static DateTime MinDateTime = new DateTime(2015, 1, 1);
        List<dynamic> selectedData = new List<dynamic>();
        string serverName = string.Empty;
        string selectedFileName = string.Empty;

        public ShowChartForm()
        {
            InitializeComponent();
        }

        private void ShowButton_Click(object sender, EventArgs e)
        {
            var maxCount = int.Parse(MaxCountTextBox.Text);

            var firstDateTime = (DateTime)selectedData[0].Date;
            var secondDateTime = (DateTime)selectedData[1].Date;
            var lastDateTime = (DateTime)selectedData[maxCount-1].Date;
            var interval = secondDateTime.Subtract(firstDateTime).TotalSeconds;
            var totalDuration = lastDateTime.Subtract(firstDateTime).TotalSeconds;
            
            RequestInfoChart.ChartAreas[0].AxisX.Maximum = maxCount;

            RequestInfoChart.Series[0].Points.Clear();
            RequestInfoChart.Series[1].Points.Clear();

            var maxConcurrentRequest = 0;
            var maxConcurrentRequestCPU = 0.0f;
            var maxConcurrentRequestDateTime = MinDateTime;


            var maxCPUConcurrentRequestNumber = 0;
            var maxCPUConcurrentRequestCPU = 0.0f;
            var maxCPUConcurrentRequestDateTime = MinDateTime;
            var concurrentRequestCountLessThan25 = 0;
            for (var index = 0; index < maxCount; index++)
            {
                var data = selectedData[index];
                var date = (DateTime)data.Date;
                var dateNumber = date.Subtract(MinDateTime).TotalSeconds;

                var count = (int)data.Count;
                var cpu = (float)data.CPU;
                if (count > maxConcurrentRequest)
                {
                    maxConcurrentRequest = count;
                    maxConcurrentRequestCPU = cpu;
                    maxConcurrentRequestDateTime = date;
                }

                if (cpu > maxCPUConcurrentRequestCPU)
                {
                    maxCPUConcurrentRequestNumber = count;
                    maxCPUConcurrentRequestCPU = cpu;
                    maxCPUConcurrentRequestDateTime = date;
                }

                if (count <= 25)
                    concurrentRequestCountLessThan25++;

                RequestInfoChart.Series[0].Points.AddXY(index + 1, count);
                RequestInfoChart.Series[1].Points.AddXY(index + 1, cpu);
            }
            
            var summaryStringBuilder = new StringBuilder();
            summaryStringBuilder.AppendLine(string.Format("Server:                                     {0}", serverName));
            summaryStringBuilder.AppendLine(string.Format("Start Date:                                 {0}", firstDateTime.ToString("MM/dd/yyyy HH:mm:ss")));
            summaryStringBuilder.AppendLine(string.Format("End Date:                                   {0}", lastDateTime.ToString("MM/dd/yyyy HH:mm:ss")));
            summaryStringBuilder.AppendLine(string.Format("Concurrent Request Number(<25) Percentage:  {0}%", Math.Round(concurrentRequestCountLessThan25 * 100.0 / maxCount, 2)));
            summaryStringBuilder.AppendLine(string.Format("Max Concurrent Request Point:               Date {0}, Number {1}, CPU {2}%", maxConcurrentRequestDateTime.ToString("MM/dd/yyyy HH:mm:ss"), maxConcurrentRequest, maxConcurrentRequestCPU));
            summaryStringBuilder.AppendLine(string.Format("Max CPU Point:                              Date {0}, Number {1}, CPU {2}%", maxCPUConcurrentRequestDateTime.ToString("MM/dd/yyyy HH:mm:ss"), maxCPUConcurrentRequestNumber, maxCPUConcurrentRequestCPU));
            SummaryLabel.Text = summaryStringBuilder.ToString();

            var bitmapFile = string.Format("{0}.gif", selectedFileName);
            var bm = new Bitmap(GraphPanel.Width, GraphPanel.Height);
            GraphPanel.DrawToBitmap(bm, new Rectangle(0,0, GraphPanel.Width, GraphPanel.Height));
            bm.Save(bitmapFile, ImageFormat.Gif);
        }

        private void SelectDataButton_Click(object sender, EventArgs e)
        {
            var openFileDialog = new OpenFileDialog(); 
            openFileDialog.ShowDialog();
            if (!string.IsNullOrEmpty(openFileDialog.FileName))
            {
                serverName = Path.GetFileNameWithoutExtension(openFileDialog.FileName);
                selectedFileName = openFileDialog.FileName;
                using (var streamReader = new StreamReader(openFileDialog.FileName))
                {
                    while (!streamReader.EndOfStream)
                    {
                        var line = streamReader.ReadLine();
                        var args = line.Split(',');
                        try
                        {
                            var date = DateTime.Parse(args[0]) ;
                            var requestCount = int.Parse(args[1]);
                            var cpu = float.Parse(args[2]);
                            selectedData.Add(new
                            {
                                Date = date,
                                Count = requestCount,
                                CPU = cpu
                            });
                        }
                        catch { }
                    }
                }
                TotalCountLabel.Text = string.Format("Total: {0}", selectedData.Count);
                DataFileTextBox.Text = openFileDialog.FileName;
                MaxCountTextBox.Text = selectedData.Count.ToString();
            }
        }

        private void ShowChartForm_Load(object sender, EventArgs e)
        {
            SummaryLabel.Text = string.Empty;
            RequestInfoChart.ChartAreas[0].AxisX.Maximum =  6000;
            //RequestInfoChart.ChartAreas[0].AxisX.Interval = RequestTimer.Interval / 1000;
            RequestInfoChart.ChartAreas[0].AxisY2.Maximum = 100;

            RequestInfoChart.ChartAreas[0].AxisY2.LineColor = Color.Transparent;
            RequestInfoChart.ChartAreas[0].AxisY2.MajorGrid.Enabled = false;
            RequestInfoChart.ChartAreas[0].AxisY2.Enabled = System.Windows.Forms.DataVisualization.Charting.AxisEnabled.True;
            RequestInfoChart.ChartAreas[0].AxisY2.IsStartedFromZero = RequestInfoChart.ChartAreas[0].AxisY.IsStartedFromZero;
        }

        private void ClearButton_Click(object sender, EventArgs e)
        {
            //RequestInfoChart.ChartAreas[0].AxisX.Maximum = maxCount;

            RequestInfoChart.ChartAreas[0].AxisX.Maximum = 6000;
            //RequestInfoChart.ChartAreas[0].AxisX.Interval = RequestTimer.Interval / 1000;
            RequestInfoChart.ChartAreas[0].AxisY2.Maximum = 100;
            RequestInfoChart.Series[0].Points.Clear();
            RequestInfoChart.Series[1].Points.Clear();
            SummaryLabel.Text = string.Empty;
        }
    }
}
